package com.zhiche.lisa.bms.service.statistics.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.zhiche.lisa.bms.dao.mapper.statistics.StaticWaybillCompositeMapper;
import com.zhiche.lisa.bms.dao.model.statistics.*;
import com.zhiche.lisa.bms.dao.model.view.FeePayablePrice;
import com.zhiche.lisa.bms.pojo.bo.statistics.BillDetailBO;
import com.zhiche.lisa.bms.pojo.bo.statistics.DeletedWaybillBO;
import com.zhiche.lisa.bms.pojo.bo.statistics.NovoPayCostBO;
import com.zhiche.lisa.bms.pojo.bo.statistics.OrderWaybillBO;
import com.zhiche.lisa.bms.pojo.vo.statistics.OrderWaybillQueryVO;
import com.zhiche.lisa.bms.pojo.vo.statistics.OrderWaybillVO;
import com.zhiche.lisa.bms.pojo.vo.statistics.WaybillCompositeVO;
import com.zhiche.lisa.bms.service.statistics.*;
import com.zhiche.lisa.bms.service.utils.OtmUtil;
import com.zhiche.lisa.bms.service.view.FeeBillService;
import com.zhiche.lisa.bms.service.view.FeePayablePriceService;
import com.zhiche.lisa.bms.utils.BmsCollectionUtils;
import com.zhiche.lisa.bms.utils.ToolCommonUtils;
import com.zhiche.lisa.core.supports.BaseException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 运单统计综合表 服务实现类
 * </p>
 *
 * @author liangpeng
 * @since 2019-01-18
 */
@Service
public class StaticWaybillCompositeServiceImpl extends ServiceImpl<StaticWaybillCompositeMapper, StaticWaybillComposite> implements StaticWaybillCompositeService {

    private final Logger LOGGER = LoggerFactory.getLogger(StaticWaybillCompositeServiceImpl.class);

    @Autowired
    private StaticWaybillService staticWaybillService;

    @Autowired
    private StaticBillDetailService staticBillDetailService;

    @Autowired
    private StaticBillService staticBillService;

    @Autowired
    private StaticPayCostService staticPayCostService;

    @Autowired
    private StaticOrderCompositeService staticOrderCompositeService;

    @Autowired
    private StaticDeleteWaybillService staticDeleteWaybillService;

    @Autowired
    private StaticUpdateOrderService staticUpdateOrderService;

    @Autowired
    private OtmUtil otmUtil;

    @Autowired
    private FeePayablePriceService feePayablePriceService;

    @Autowired
    private FeeBillService feeBillService;


    private static final String OTHER_PRICE = "其他费用";

    private static final String TRANSPORT_PRICE = "运输费";

    private static final String CONTRACT_PRICE = "合同价";

    private static final String STAND_PRICE = "暂估价";

    @Autowired
    private StaticNovoPayCostService staticNovoPayCostService;

    /**
     * 运单统计综合查询分页
     *
     * @param page
     */
    @Override
    public Page<OrderWaybillVO> getOrderWaybillDetail(Page<OrderWaybillBO> page) {
        if (page == null) {
            return null;
        }
        EntityWrapper<OrderWaybillBO> ew = whereCondition(page);
        ew.orderBy("print_date");
        Page<OrderWaybillVO> pageVo = new Page<>();
        List<OrderWaybillBO> list = baseMapper.getOrderWaybillDetailBO(page, ew);
        BeanUtils.copyProperties(page, pageVo);
        List<OrderWaybillVO> lists = Lists.newArrayList();
        list.forEach(orderWaybillBO -> {
            OrderWaybillVO orderWaybillVO = new OrderWaybillVO();
            BeanUtils.copyProperties(orderWaybillBO, orderWaybillVO);
            lists.add(orderWaybillVO);
        });
        if (CollectionUtils.isEmpty(lists)) {
            OrderWaybillVO orderWaybillVO = new OrderWaybillVO();
            lists.add(orderWaybillVO);
        }
        pageVo.setRecords(lists);
        return pageVo;
    }

    /**
     * 根据条件查询所有符合要求的运单统计综合查询
     *
     * @param queryVO
     * @return
     */
    @Override
    public List<OrderWaybillVO> queryOrderWaybillDetail(OrderWaybillQueryVO queryVO) {
        if (Objects.isNull(queryVO)) {
            return null;
        }
        // EntityWrapper<OrderWaybillBO> ew = whereCondition(queryVO);
        // ew.orderBy("print_date");
        // List<OrderWaybillBO> list = baseMapper.getOrderWaybillDetailBO(ew);
        // List<OrderWaybillVO> lists = Lists.newArrayList();
        // list.forEach(orderWaybillBO -> {
        //     OrderWaybillVO orderWaybillVO = new OrderWaybillVO();
        //     BeanUtils.copyProperties(orderWaybillBO, orderWaybillVO);
        //     if (StringUtils.isNotBlank(orderWaybillVO.getSysOrderId())) {
        //         orderWaybillVO.setSysOrderId("ULC/ZC." + orderWaybillVO.getSysOrderId());
        //     }
        //     if (StringUtils.isNotBlank(orderWaybillVO.getSysWaybillId())) {
        //         orderWaybillVO.setSysWaybillId("ULC/ZC." + orderWaybillVO.getSysWaybillId());
        //     }
        //     lists.add(orderWaybillVO);
        // });
        Page<OrderWaybillBO> page = new Page<>();
        page.setCurrent(1);
        page.setSize(10000);
        EntityWrapper<OrderWaybillBO> ew = whereCondition(queryVO);
        ew.orderBy("print_date, sys_order_id asc");
        // List<OrderWaybillBO> list = baseMapper.getOrderWaybillDetailBO(ew);
        List<OrderWaybillBO> allDataList = Lists.newArrayList();
        List<OrderWaybillBO> list = baseMapper.getOrderWaybillDetailBOForExport(page, ew);
        int pages = page.getPages();
        if (pages > 1) {
            allDataList.addAll(list);
            for (int i = 2; i <= pages; i++) {
                page.setCurrent(i);
                allDataList.addAll(baseMapper.getOrderWaybillDetailBOForExport(page, ew));
            }
        } else {
            allDataList.addAll(list);
        }
        List<OrderWaybillVO> lists = Lists.newArrayList();
        allDataList.forEach(orderWaybillBO -> {
            OrderWaybillVO orderWaybillVO = new OrderWaybillVO();
            BeanUtils.copyProperties(orderWaybillBO, orderWaybillVO);
            if (StringUtils.isNotBlank(orderWaybillVO.getSysOrderId())) {
                orderWaybillVO.setSysOrderId("ULC/ZC." + orderWaybillVO.getSysOrderId());
            }
            if (StringUtils.isNotBlank(orderWaybillVO.getSysWaybillId())) {
                orderWaybillVO.setSysWaybillId("ULC/ZC." + orderWaybillVO.getSysWaybillId());
            }
            lists.add(orderWaybillVO);
        });
        if (CollectionUtils.isEmpty(lists)) {
            OrderWaybillVO orderWaybillVO = new OrderWaybillVO();
            lists.add(orderWaybillVO);
        }
        return lists;
    }

    /**
     * 创建运单综合统计表
     */
    @Override
    public void insertWaybillComposite() {
        try {
            int nThreads = 5;

            // 查询运单发生变化
            LOGGER.info("updateWaybill start");
            updateWaybill(nThreads, 0);
            LOGGER.info("updateWaybill end");

            // 排除已经删除的运单
            LOGGER.info("getDeletedWaybill start");
            getDeletedWaybill(nThreads, 0);
            LOGGER.info("getDeletedWaybill end");

            // 查询账单发生变化
            LOGGER.info("updateBill start");
            updateBill(nThreads, 0);
            LOGGER.info("updateBill end");

            // 查询价格发生变化
            LOGGER.info("updateNovoPayCost start");
            updateNovoPayCost(nThreads, 0);
            LOGGER.info("updateNovoPayCost end");

            // 更新合同价和暂估价
            LOGGER.info("updateWaybillContractAndEstPrice start");
            updateWaybillContractAndEstPrice(nThreads, 0);
            LOGGER.info("updateWaybillContractAndEstPrice end");

            // 更新分摊金额
            LOGGER.info("updateAmount start");
            updateAmount(nThreads, 0);
            LOGGER.info("updateAmount end");
        } catch (Exception ex) {
            throw new BaseException(ex.getMessage());
        }
    }


    /**
     * 更新运单发生变化
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWaybill(int nThreads, int intCount) {
        //查询发生变化的运单
        List<StaticWaybill> listWaybill = staticWaybillService.getStaticWayBillByOrder(intCount);
        if (CollectionUtils.isNotEmpty(listWaybill)) {
            // listWaybill.forEach(staticWaybill -> addUpdateOrders(staticWaybill.getSysOrderId()));
            List<String> sysOrderIdList = Lists.newArrayList();
            listWaybill.forEach(waybill -> {
                sysOrderIdList.add(waybill.getSysOrderId());
            });
            if (CollectionUtils.isNotEmpty(sysOrderIdList)) {
                addOrUpdateOrder(sysOrderIdList);
            }

            ExecutorService executorService1 = Executors.newFixedThreadPool(nThreads);
            int size = listWaybill.size();
            if (size <= 10) {
                nThreads = 1;
            }
            int remaider = size % nThreads;  //(先计算出余数)
            int number = size / nThreads;  //然后是商
            int offset = 0;//偏移量
            try {
                for (int i = 0; i < nThreads; i++) {
                    // 先分组
                    if (remaider > 0) {
                        final List<StaticWaybill> enrollList = listWaybill.subList(i * number + offset, (i + 1) * number + offset + 1);
                        // this.updateWaybill(enrollList);
                        // List<StaticWaybill> newList = enrollList.stream().filter(staticWaybill -> staticWaybill.getDomain().equals("ULC/ZC") && !staticWaybill.getStatus().equals("已取消")).collect(Collectors.toList());
                        // this.insertStandPrice(newList);
                        executorService1.execute(() -> {
                            // 检查是否共享线程
                            LOGGER.info("测试 -> {}, {}", Thread.currentThread().getName(), Thread.currentThread().isDaemon());
                            this.updateWaybill(enrollList);
                            // List<StaticWaybill> newList = enrollList.stream().filter(staticWaybill -> staticWaybill.getDomain().equals("ULC/ZC") && !staticWaybill.getStatus().equals("已取消")).collect(Collectors.toList());
                            // this.insertStandPrice(newList);
                        });
                        remaider--;
                        offset++;
                    } else {
                        final List<StaticWaybill> enrollList = listWaybill.subList(i * number + offset, (i + 1) * number + offset);
                        // this.updateWaybill(enrollList);
                        // List<StaticWaybill> newList = enrollList.stream().filter(staticWaybill -> staticWaybill.getDomain().equals("ULC/ZC") && !staticWaybill.getStatus().equals("已取消")).collect(Collectors.toList());
                        // this.insertStandPrice(newList);
                        executorService1.execute(() -> {
                            // 检查是否共享线程
                            LOGGER.info("测试 -> {}, {}", Thread.currentThread().getName(), Thread.currentThread().isDaemon());
                            this.updateWaybill(enrollList);
                            // List<StaticWaybill> newList = enrollList.stream().filter(staticWaybill -> staticWaybill.getDomain().equals("ULC/ZC") && !staticWaybill.getStatus().equals("已取消")).collect(Collectors.toList());
                            // this.insertStandPrice(newList);
                        });
                    }
                }
                executorService1.shutdown();
                while (!executorService1.awaitTermination(60, TimeUnit.SECONDS)) {
                    LOGGER.info("线程池没有关闭");
                }
                LOGGER.info("线程池已经关闭");
            } catch (Exception ex) {
                throw new BaseException(ex.getMessage());
            }
        }
    }


    /**
     * 计算更新的运单的标准价
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWaybillStandPrice(int nThreads, int intCount) {
        //查询发生变化的运单
        List<StaticWaybill> listWaybill = staticWaybillService.getNoStandPriceWaybill(intCount);
        if (CollectionUtils.isNotEmpty(listWaybill)) {
            ExecutorService executorService1 = Executors.newFixedThreadPool(nThreads);
            int size = listWaybill.size();
            if (size <= 10) {
                nThreads = 1;
            }
            int remaider = size % nThreads;  //(先计算出余数)
            int number = size / nThreads;  //然后是商
            int offset = 0;//偏移量
            try {
                for (int i = 0; i < nThreads; i++) {
                    // 先分组
                    if (remaider > 0) {
                        final List<StaticWaybill> enrollList = listWaybill.subList(i * number + offset, (i + 1) * number + offset + 1);
                        // this.insertStandPrice(enrollList);
                        executorService1.execute(() -> {
                            // 检查是否共享线程
                            LOGGER.info("测试 -> {}, {}", Thread.currentThread().getName(), Thread.currentThread().isDaemon());
                            this.insertStandPrice(enrollList);
                        });
                        remaider--;
                        offset++;
                    } else {
                        final List<StaticWaybill> enrollList = listWaybill.subList(i * number + offset, (i + 1) * number + offset);
                        // this.insertStandPrice(enrollList);
                        executorService1.execute(() -> {
                            // 检查是否共享线程
                            LOGGER.info("测试 -> {}, {}", Thread.currentThread().getName(), Thread.currentThread().isDaemon());
                            this.insertStandPrice(enrollList);
                        });
                    }
                }
                executorService1.shutdown();
                while (!executorService1.awaitTermination(60, TimeUnit.SECONDS)) {
                    LOGGER.info("线程池没有关闭");
                }
                LOGGER.info("线程池已经关闭");
            } catch (Exception ex) {
                throw new BaseException(ex.getMessage());
            }
        }
    }


    /**
     * 得到删除的运单
     *
     * @param nThreads
     * @param intCount
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void getDeletedWaybill(int nThreads, int intCount) {
        //查询发生变化的运单
        List<DeletedWaybillBO> listDeletedWaybillBo = staticDeleteWaybillService.getStaticDeleteWayBill(intCount);
        if (CollectionUtils.isNotEmpty(listDeletedWaybillBo)) {
            // listDeletedWaybillBo.forEach(staticWaybill -> addUpdateOrders(staticWaybill.getSysOrderId()));
            List<String> sysOrderIdList = Lists.newArrayList();
            listDeletedWaybillBo.forEach(dtl -> {
                sysOrderIdList.add(dtl.getSysOrderId());
            });
            if (CollectionUtils.isNotEmpty(sysOrderIdList)) {
                addOrUpdateOrder(sysOrderIdList);
            }
            ExecutorService executorService1 = Executors.newFixedThreadPool(nThreads);
            int size = listDeletedWaybillBo.size();
            if (size <= 10) {
                nThreads = 1;
            }
            int remaider = size % nThreads;  //(先计算出余数)
            int number = size / nThreads;  //然后是商
            int offset = 0;//偏移量

            try {
                for (int i = 0; i < nThreads; i++) {
                    // 先分组
                    if (remaider > 0) {
                        final List<DeletedWaybillBO> enrollList = listDeletedWaybillBo.subList(i * number + offset, (i + 1) * number + offset + 1);
                        // this.deleteWaybill(enrollList);
                        executorService1.execute(() -> {
                            // 检查是否共享线程
                            LOGGER.info("测试 -> {}, {}", Thread.currentThread().getName(), Thread.currentThread().isDaemon());
                            this.deleteWaybill(enrollList);
                        });
                        remaider--;
                        offset++;
                    } else {
                        final List<DeletedWaybillBO> enrollList = listDeletedWaybillBo.subList(i * number + offset, (i + 1) * number + offset);
                        // this.deleteWaybill(enrollList);
                        executorService1.execute(() -> {
                            // 检查是否共享线程
                            LOGGER.info("测试 -> {}, {}", Thread.currentThread().getName(), Thread.currentThread().isDaemon());
                            this.deleteWaybill(enrollList);
                        });
                    }
                }
                executorService1.shutdown();
                while (!executorService1.awaitTermination(60, TimeUnit.SECONDS)) {
                    LOGGER.info("线程池没有关闭");
                }
                LOGGER.info("线程池已经关闭");
            } catch (Exception ex) {
                throw new BaseException(ex.getMessage());
            }
        }
    }


    /**
     * 更新发生变化的账单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBill(int nThreads, int intCount) {
        //查询账单发生变化
        List<BillDetailBO> listBillDetailBO = staticBillDetailService.getAPBillDetailBO(intCount);
        if (CollectionUtils.isNotEmpty(listBillDetailBO)) {
            // listBillDetailBO.forEach(billDetailBO -> addUpdateOrders(billDetailBO.getSysOrderId()));
            List<String> sysOrderIdList = Lists.newArrayList();
            listBillDetailBO.forEach(waybill -> {
                sysOrderIdList.add(waybill.getSysOrderId());
            });
            if (CollectionUtils.isNotEmpty(sysOrderIdList)) {
                addOrUpdateOrder(sysOrderIdList);
            }

            int size = listBillDetailBO.size();
            if (size <= 10) {
                nThreads = 1;
            }
            ExecutorService executorService1 = Executors.newFixedThreadPool(nThreads);
            int remaider = size % nThreads;  //(先计算出余数)
            int number = size / nThreads;  //然后是商
            int offset = 0;//偏移量
            try {
                for (int i = 0; i < nThreads; i++) {
                    // 先分组
                    if (remaider > 0) {
                        final List<BillDetailBO> enrollList = listBillDetailBO.subList(i * number + offset, (i + 1) * number + offset + 1);
                        executorService1.execute(() -> {
                            this.updateBill(enrollList);
                        });
                        remaider--;
                        offset++;
                    } else {
                        final List<BillDetailBO> enrollList = listBillDetailBO.subList(i * number + offset, (i + 1) * number + offset);
                        executorService1.execute(() -> {
                            this.updateBill(enrollList);
                        });
                    }
                }
                executorService1.shutdown();
                while (!executorService1.awaitTermination(60, TimeUnit.SECONDS)) {
                    LOGGER.info("updateBill: 线程池没有关闭");
                }
                LOGGER.info("updateBill: 线程池已经关闭");
            } catch (Exception ex) {
                LOGGER.error("updateBill {}", ex);
                throw new BaseException(ex.getMessage());
            }
        }
    }

    // /**
    //  * 更新发生变化的价格
    //  */
    // @Override
    // @Transactional(rollbackFor = Exception.class)
    // public void updatePrice(int nThreads, int intCount) {
    //     //查询未处理的支付价格
    //     Wrapper<StaticPayCost> ew = new EntityWrapper<>();
    //     // ew.in("sys_waybill_id", getSysWaybillId());
    //     List<StaticPayCost> distinctListPayCost = staticPayCostService.getDistinctPayCostNoDeal(intCount, ew);
    //     if (CollectionUtils.isNotEmpty(distinctListPayCost)) {
    //         // distinctListPayCost.forEach(staticPayCost -> addUpdateOrders(staticPayCost.getSysOrderId()));
    //         List<String> sysOrderIdList = Lists.newArrayList();
    //         distinctListPayCost.forEach(cost -> {
    //             sysOrderIdList.add(cost.getSysOrderId());
    //         });
    //         if (CollectionUtils.isNotEmpty(sysOrderIdList)) {
    //             addOrUpdateOrder(sysOrderIdList);
    //         }
    //
    //         ExecutorService executorService1 = Executors.newFixedThreadPool(nThreads);
    //         int size = distinctListPayCost.size();
    //         if (size <= 10) {
    //             nThreads = 1;
    //         }
    //         int remaider = size % nThreads;  //(先计算出余数)
    //         int number = size / nThreads;  //然后是商
    //         int offset = 0;//偏移量
    //         try {
    //             for (int i = 0; i < nThreads; i++) {
    //                 // 先分组
    //                 if (remaider > 0) {
    //                     final List<StaticPayCost> enrollList = distinctListPayCost.subList(i * number + offset, (i + 1) * number + offset + 1);
    //                     // this.updatePrice(enrollList);
    //                     // this.updateStandPrice(enrollList);
    //                     // this.updatePayCostStatus(enrollList);
    //                     executorService1.execute(() -> {
    //                         // 检查是否共享线程
    //                         LOGGER.info("测试 -> {}, {}", Thread.currentThread().getName(), Thread.currentThread().isDaemon());
    //                         this.updatePrice(enrollList);
    //                         // this.updateStandPrice(enrollList);
    //                         // this.updatePayCostStatus(enrollList);
    //                     });
    //                     remaider--;
    //                     offset++;
    //                 } else {
    //                     final List<StaticPayCost> enrollList = distinctListPayCost.subList(i * number + offset, (i + 1) * number + offset);
    //                     // this.updatePrice(enrollList);
    //                     // this.updateStandPrice(enrollList);
    //                     // this.updatePayCostStatus(enrollList);
    //                     executorService1.execute(() -> {
    //                         // 检查是否共享线程
    //                         LOGGER.info("测试 -> {}, {}", Thread.currentThread().getName(), Thread.currentThread().isDaemon());
    //                         this.updatePrice(enrollList);
    //                         // this.updateStandPrice(enrollList);
    //                         // this.updatePayCostStatus(enrollList);
    //                     });
    //                 }
    //             }
    //             executorService1.shutdown();
    //             while (!executorService1.awaitTermination(60, TimeUnit.SECONDS)) {
    //                 LOGGER.info("线程池没有关闭");
    //             }
    //             LOGGER.info("线程池已经关闭");
    //         } catch (Exception ex) {
    //             LOGGER.error("updatePrice {}", ex);
    //             throw new BaseException(ex.getMessage());
    //         }
    //     }
    // }

    /**
     * 更新发生变化的价格
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateNovoPayCost(int nThreads, int intCount) {
        //查询未处理的支付价格
        List<NovoPayCostBO> distinctListPayCostList = staticNovoPayCostService.getDistinctWaybillPayCostNoDeal(intCount);
        if (CollectionUtils.isNotEmpty(distinctListPayCostList)) {
            List<String> sysOrderIdList = Lists.newArrayList();
            distinctListPayCostList.forEach(payCost -> {
                sysOrderIdList.add(payCost.getSysOrderId());
            });
            if (CollectionUtils.isNotEmpty(sysOrderIdList)) {
                addOrUpdateOrder(sysOrderIdList);
            }

            ExecutorService executorService1 = Executors.newFixedThreadPool(nThreads);
            int size = distinctListPayCostList.size();
            if (size <= 10) {
                nThreads = 1;
            }
            int remaider = size % nThreads;  //(先计算出余数)
            int number = size / nThreads;  //然后是商
            int offset = 0;//偏移量
            try {
                for (int i = 0; i < nThreads; i++) {
                    // 先分组
                    if (remaider > 0) {
                        List<NovoPayCostBO> subPayCostDataList = distinctListPayCostList.subList(i * number + offset, (i + 1) * number + offset + 1);
                        executorService1.execute(() -> {
                            LOGGER.info("处理成本数据 -> {}, {}", Thread.currentThread().getName(), Thread.currentThread().isDaemon());
                            this.dealPayCostData(subPayCostDataList);
                        });
                        remaider--;
                        offset++;
                    } else {
                        List<NovoPayCostBO> subPayCostDataList = distinctListPayCostList.subList(i * number + offset, (i + 1) * number + offset);
                        executorService1.execute(() -> {
                            LOGGER.info("处理成本数据 -> {}, {}", Thread.currentThread().getName(), Thread.currentThread().isDaemon());
                            this.dealPayCostData(subPayCostDataList);
                        });
                    }
                }
                executorService1.shutdown();
                while (!executorService1.awaitTermination(60, TimeUnit.SECONDS)) {
                    LOGGER.info("处理成本数据线程池没有关闭");
                }
                LOGGER.info("处理成本数据线程池已经关闭");
            } catch (Exception ex) {
                LOGGER.error("updateNovoPayCost {}", ex);
                throw new BaseException(ex.getMessage());
            }
        }
    }


    //更新运单
    private void updateWaybill(List<StaticWaybill> listWaybill) {
        Date date = new Date();
        try {
            if (CollectionUtils.isNotEmpty(listWaybill)) {
                Set<String> sysWaybillIdSet = Sets.newHashSet();
                listWaybill.forEach(staticWaybill -> {
                    if ("已取消".equals(staticWaybill.getStatus()) || "delete".equals(staticWaybill.getCancelFlag())) {
                        staticWaybill.setIsDelete(1);
                        // EntityWrapper<StaticWaybillComposite> ewWaybill = new EntityWrapper<>();
                        // ewWaybill.eq("sys_waybill_id", staticWaybill.getSysWaybillId());
                        // this.delete(ewWaybill);
                        sysWaybillIdSet.add(staticWaybill.getSysWaybillId());
                    }
                    staticWaybill.setDealStatus(1);
                    staticWaybill.setDealTime(date);
                });
                if (CollectionUtils.isNotEmpty(sysWaybillIdSet)) {
                    EntityWrapper<StaticWaybillComposite> ewWaybill = new EntityWrapper<>();
                    ewWaybill.in("sys_waybill_id", sysWaybillIdSet);
                    this.delete(ewWaybill);
                }
                //更新原有运单状态
                if (CollectionUtils.isNotEmpty(listWaybill)) {
                    staticWaybillService.updateBatchById(listWaybill);
                }
            }
        } catch (Exception ex) {
            LOGGER.error("updateWaybill {}", ex);
            throw new BaseException(ex.getMessage());
        }
    }

    //插入标准价
    private void insertStandPrice(List<StaticWaybill> listWaybill) {
        if (CollectionUtils.isNotEmpty(listWaybill)) {
            Set<StaticPayCost> setPay = new HashSet<>();
            listWaybill.forEach(staticWaybill -> {
                //去OTM取标准价
                Map<String, Double> map = otmUtil.getStdPriceMap(staticWaybill.getSysWaybillId());
                if (MapUtils.isNotEmpty(map)) {
                    StaticPayCost standPayCost = new StaticPayCost();
                    standPayCost.setSysOrderId(staticWaybill.getSysOrderId());
                    standPayCost.setCustWaybillId(staticWaybill.getCustWaybillId());
                    standPayCost.setShipmentCode(staticWaybill.getShipmentCode());
                    standPayCost.setSysWaybillId(staticWaybill.getSysWaybillId());
                    standPayCost.setCostType("运输费");
                    standPayCost.setPriceType("标准价");
                    BigDecimal price = new BigDecimal(map.get("price"));
                    BigDecimal miles = new BigDecimal(map.get("miles"));
                    BigDecimal money = price.multiply(miles);
                    standPayCost.setPrice(price);
                    standPayCost.setMiles(miles);
                    standPayCost.setMoney(money);
                    setPay.add(standPayCost);
                }
            });

            if (CollectionUtils.isNotEmpty(setPay)) {
                List<StaticPayCost> lists = new ArrayList<>(setPay);
                staticPayCostService.insertBatch(lists);
            }
        }
    }

    //更新账单
    private void updateBill(List<BillDetailBO> listBillDetailBO) {
        Date date = new Date();
        // List<StaticBill> listBill = Lists.newArrayList();
        // List<StaticBillDetail> listBillDetail = Lists.newArrayList();

        Set<Long> billHeadIdSet = new HashSet<>();
        Set<Long> billDetailIdSet = new HashSet<>();

        // 2019-09-26 去除账单其他费用
        // Map<String, BigDecimal> incomeBillChargeMap = Maps.newHashMap();

        try {

            listBillDetailBO.forEach(billDetailBO -> {
                // BigDecimal billCharge = Objects.nonNull(billDetailBO.getPayBillCharge()) ? billDetailBO.getPayBillCharge() : BigDecimal.ZERO;
                // 2019-05-20 更换字段
                BigDecimal billOtherFee = Objects.nonNull(billDetailBO.getBillOtherFee()) ? billDetailBO.getBillOtherFee() : BigDecimal.ZERO;
                // 实付金额
                BigDecimal actualMoney = Objects.nonNull(billDetailBO.getActualMoney()) ? billDetailBO.getActualMoney() : BigDecimal.ZERO;

                // EntityWrapper<StaticBillDetail> ewBillDetail = new EntityWrapper<>();
                // ewBillDetail.eq("bill_id", billDetailBO.getBillId());
                // int waybillCount = staticBillDetailService.selectCount(ewBillDetail);

                //平均分配每个运单的账单的金额
                // BigDecimal everyBillCharge = BigDecimal.ZERO;
                // if (waybillCount > 0) {
                //     everyBillCharge = billCharge.divide(new BigDecimal(waybillCount), 2, RoundingMode.HALF_UP);
                // }

                // 2019-09-26 去除账单其他费用
                // BigDecimal everyBillCharge = incomeBillChargeMap.get(billDetailBO.getBillId());
                // if (Objects.isNull(everyBillCharge)) {
                //
                //     // 计算条数
                //     int waybillCount = getBillDetailDistinctCount(billDetailBO.getBillId());
                //     //平均分配每个订单的账单的金额
                //     everyBillCharge = BigDecimal.ZERO;
                //     if (waybillCount > 0) {
                //         // everyBillCharge = billCharge.divide(new BigDecimal(waybillCount), 2, RoundingMode.HALF_UP);
                //         everyBillCharge = billOtherFee.divide(new BigDecimal(waybillCount), 2, RoundingMode.HALF_UP);
                //     }
                //     incomeBillChargeMap.put(billDetailBO.getBillId(), everyBillCharge);
                // }

                // EntityWrapper<StaticWaybillComposite> ewStaticWaybillComposite = new EntityWrapper<>();
                // ewStaticWaybillComposite.eq("sys_order_id", billDetailBO.getSysOrderId())
                //         .eq("sys_waybill_id", billDetailBO.getSysWaybillId());
                // StaticWaybillComposite staticWaybillComposite = this.selectOne(ewStaticWaybillComposite);
                StaticWaybillComposite staticWaybillComposite = this.selectById(billDetailBO.getWaybillCompositeId());
                if (Objects.nonNull(staticWaybillComposite)) {
                    if (StringUtils.isNotEmpty(billDetailBO.getBillId())) {
                        staticWaybillComposite.setPayBillId(billDetailBO.getBillId());
                    }

                    if (StringUtils.isNotEmpty(billDetailBO.getBillStatus())) {
                        staticWaybillComposite.setPayBillStatus(billDetailBO.getBillStatus());
                    }

                    if (StringUtils.isNotEmpty(billDetailBO.getPayInvoiceNo())) {
                        staticWaybillComposite.setPayInvoiceNo(billDetailBO.getPayInvoiceNo());
                    }

                    if (StringUtils.isNotEmpty(billDetailBO.getPayInvoiceCode())) {
                        staticWaybillComposite.setPayInvoiceCode(billDetailBO.getPayInvoiceCode());
                    }

                    if (StringUtils.isNotEmpty(billDetailBO.getPayInvoiceDate())) {
                        staticWaybillComposite.setPayInvoiceDate(billDetailBO.getPayInvoiceDate());
                    }

                    // if (StringUtils.isNotEmpty(billDetailBO.getPayName())) {
                    //     staticWaybillComposite.setPayName(billDetailBO.getPayName());
                    // }

                    if (StringUtils.isNotEmpty(billDetailBO.getPayDate())) {
                        staticWaybillComposite.setPayDate(billDetailBO.getPayDate());
                    }

                    if (StringUtils.isNotEmpty(billDetailBO.getReceiveInvoiceDate())) {
                        staticWaybillComposite.setReceiveInvoiceDate(billDetailBO.getReceiveInvoiceDate());
                    }

                    // if (Objects.nonNull(billDetailBO.getPayBillCharge())) {
                    //     staticWaybillComposite.setPayBillCharge(billDetailBO.getPayBillCharge());
                    // }

                    // if (Objects.nonNull(billDetailBO.getActualMoney())) {
                    //     // actualMoney 实付金额
                    //     if (Objects.nonNull(staticWaybillComposite.getPayMoney())) {
                    //         staticWaybillComposite.setPayMoney(staticWaybillComposite.getPayMoney().add(actualMoney));
                    //     } else {
                    //         staticWaybillComposite.setPayMoney(actualMoney);
                    //     }
                    // }
                    if (Objects.nonNull(actualMoney)) {
                        // actualMoney 实付金额
                        if (Objects.nonNull(staticWaybillComposite.getPayMoney())) {
                            staticWaybillComposite.setPayMoney(staticWaybillComposite.getPayMoney().add(actualMoney));
                        } else {
                            staticWaybillComposite.setPayMoney(actualMoney);
                        }
                    }

                    // 2019-09-26 去除账单其他费用
                    // if (Objects.nonNull(everyBillCharge)) {
                    //     // if (Objects.nonNull(staticWaybillComposite.getPayBillOtherCost())) {
                    //     //     staticWaybillComposite.setPayBillOtherCost(staticWaybillComposite.getPayBillOtherCost().add(everyBillCharge));
                    //     // } else {
                    //     //     staticWaybillComposite.setPayBillOtherCost(everyBillCharge);
                    //     // }
                    //     staticWaybillComposite.setPayBillOtherCost(everyBillCharge);
                    // }

                    this.updateById(staticWaybillComposite);
                }

                // EntityWrapper<StaticBill> ewStaticBill = new EntityWrapper<>();
                // ewStaticBill.eq("bill_id", billDetailBO.getBillId())
                //         .eq("deal_status", "0");
                // StaticBill staticBill = staticBillService.selectOne(ewStaticBill);
                // if (Objects.nonNull(staticBill)) {
                //     staticBill.setDealStatus(1);
                //     staticBill.setDealTime(date);
                //     listBill.add(staticBill);
                // }
                billHeadIdSet.add(billDetailBO.getId());

                // EntityWrapper<StaticBillDetail> ewStaticBillDetail = new EntityWrapper<>();
                // ewStaticBillDetail.eq("bill_id", billDetailBO.getBillId())
                //         .eq("deal_status", "0")
                //         .eq("sys_waybill_id", billDetailBO.getSysWaybillId());
                // StaticBillDetail staticBillDetail = staticBillDetailService.selectOne(ewStaticBillDetail);
                // if (Objects.nonNull(staticBillDetail)) {
                //     staticBillDetail.setDealStatus(1);
                //     staticBillDetail.setDealTime(date);
                //     listBillDetail.add(staticBillDetail);
                // }
                billDetailIdSet.add(billDetailBO.getBillDetailId());
            });

            //更新原有账单状态
            // if (CollectionUtils.isNotEmpty(listBill)) {
            //     staticBillService.updateBatchById(listBill);
            // }
            if (CollectionUtils.isNotEmpty(billHeadIdSet)) {
                List<StaticBill> billList = Lists.newArrayList();
                billHeadIdSet.forEach(billHeadId -> {
                    StaticBill staticBill = new StaticBill();
                    staticBill.setId(billHeadId);
                    staticBill.setDealStatus(1);
                    staticBill.setDealTime(date);
                    billList.add(staticBill);
                });
                staticBillService.updateBatchById(billList);
            }

            // if (CollectionUtils.isNotEmpty(listBillDetail)) {
            //     staticBillDetailService.updateBatchById(listBillDetail);
            // }
            if (CollectionUtils.isNotEmpty(billDetailIdSet)) {
                List<StaticBillDetail> billDetailList = Lists.newArrayList();
                billDetailIdSet.forEach(billDetailId -> {
                    StaticBillDetail staticBillDetail = new StaticBillDetail();
                    staticBillDetail.setId(billDetailId);
                    staticBillDetail.setDealStatus(1);
                    staticBillDetail.setDealTime(date);
                    billDetailList.add(staticBillDetail);
                });
                staticBillDetailService.updateBatchById(billDetailList);
            }
        } catch (Exception ex) {
            LOGGER.error("updateBill {}", ex);
            throw new BaseException(ex.getMessage());
        }
    }

    /**
     * 计算订单数量
     *
     * @param billId
     * @return
     */
    private int getBillDetailDistinctCount(String billId) {
        int count = 0;
        EntityWrapper<StaticBillDetail> ewBillDetail = new EntityWrapper<>();
        ewBillDetail.setSqlSelect("distinct sys_order_id");
        ewBillDetail.eq("bill_id", billId);
        List<Object> objectList = staticBillDetailService.selectObjs(ewBillDetail);
        if (CollectionUtils.isNotEmpty(objectList)) {
            return objectList.size();
        }
        return count;
    }


    // /**
    //  * 更新正式价格
    //  *
    //  * @param distinctListPayCost
    //  */
    // private void updatePrice(List<StaticPayCost> distinctListPayCost) {
    //
    //     List<String> sysWaybillIdList = Lists.newArrayList();
    //     Date dealDate = new Date();
    //
    //     try {
    //         List<StaticWaybillComposite> updateWaybillCompositeList = Lists.newArrayList();
    //         distinctListPayCost.forEach(staticPayCost -> {
    //             EntityWrapper<StaticWaybillComposite> ewStaticWaybillComposite = new EntityWrapper<>();
    //             ewStaticWaybillComposite.eq("sys_order_id", staticPayCost.getSysOrderId())
    //                     .eq("sys_waybill_id", staticPayCost.getSysWaybillId());
    //             StaticWaybillComposite staticWaybillComposite = this.selectOne(ewStaticWaybillComposite);
    //
    //             if (Objects.nonNull(staticWaybillComposite)) {
    //                 EntityWrapper<StaticPayCost> staticPayCostEntityWrapper = new EntityWrapper<>();
    //                 // staticPayCostEntityWrapper
    //                 //         .eq("sys_waybill_id", staticPayCost.getSysWaybillId())
    //                 //         .eq("cost_type", "运输费")
    //                 //         .ne("price_type", "标准价");
    //                 staticPayCostEntityWrapper.eq("sys_waybill_id", staticPayCost.getSysWaybillId());
    //
    //                 List<StaticPayCost> lists = staticPayCostService.selectList(staticPayCostEntityWrapper);
    //
    //                 //正式
    //                 int dealTimeSize = 0;
    //                 int normalDataSize = 0;
    //                 for (StaticPayCost payCost : lists) {
    //                     if ("应付".equals(payCost.getPriceType()) && "运输费".equals(payCost.getCostType())
    //                             && !"标准价".equals(payCost.getPriceType())) {
    //                         normalDataSize++;
    //                         if (Objects.nonNull(payCost.getBmsDealTime())) {
    //                             dealTimeSize++;
    //                         }
    //                     }
    //                 }
    //                 Optional<StaticPayCost> cost1 = null;
    //                 if (dealTimeSize != 0 && dealTimeSize == normalDataSize) {
    //                     cost1 = lists.stream()
    //                             .filter(cost -> "应付".equals(cost.getPriceType()) && "运输费".equals(cost.getCostType()) && !"标准价".equals(cost.getPriceType()))
    //                             .max(Comparator.comparing(StaticPayCost::getBmsDealTime));
    //                 } else {
    //                     cost1 = lists.stream()
    //                             .filter(cost -> "应付".equals(cost.getPriceType()) && "运输费".equals(cost.getCostType()) && !"标准价".equals(cost.getPriceType()))
    //                             .max(Comparator.comparing(StaticPayCost::getGmtModify));
    //                 }
    //                 // Optional<StaticPayCost> cost1 = lists.stream()
    //                 //         .filter(cost -> "应付".equals(cost.getPriceType()) && "运输费".equals(cost.getCostType()) && !"标准价".equals(cost.getPriceType()))
    //                 //         .max(Comparator.comparing(StaticPayCost::getGmtModify));
    //                 if (cost1.isPresent()) {
    //                     staticWaybillComposite.setWaybillPrice(cost1.get().getPrice());
    //                     staticWaybillComposite.setWaybillMiles(cost1.get().getMiles());
    //                     staticWaybillComposite.setWaybillMoney(cost1.get().getMoney());
    //                     staticWaybillComposite.setIsEst("否");
    //                     // 合同编码
    //                     staticWaybillComposite.setContractId(cost1.get().getContractId());
    //                     // 规则id
    //                     staticWaybillComposite.setQuoteCode(cost1.get().getRuleId());
    //                     // 支付主体
    //                     staticWaybillComposite.setPayName(cost1.get().getUnlcnName());
    //                 } else {
    //                     staticWaybillComposite.setWaybillPrice(BigDecimal.ZERO);
    //                     staticWaybillComposite.setWaybillMiles(BigDecimal.ZERO);
    //                     staticWaybillComposite.setWaybillMoney(BigDecimal.ZERO);
    //                 }
    //
    //                 //暂估
    //                 int estDealTimeSize = 0;
    //                 int estNormalDataSize = 0;
    //                 for (StaticPayCost payCost : lists) {
    //                     if (StringUtils.isNotBlank(payCost.getPriceType())
    //                             && payCost.getPriceType().contains("暂估") && "运输费".equals(payCost.getCostType()) && !"标准价".equals(payCost.getPriceType())) {
    //                         estNormalDataSize++;
    //                         if (Objects.nonNull(payCost.getBmsDealTime())) {
    //                             estDealTimeSize++;
    //                         }
    //                     }
    //                 }
    //                 Optional<StaticPayCost> cost2 = null;
    //                 if (estDealTimeSize != 0 && estDealTimeSize == estNormalDataSize) {
    //                     cost2 = lists.stream()
    //                             .filter(cost -> StringUtils.isNotBlank(cost.getPriceType())
    //                                     && cost.getPriceType().contains("暂估") && "运输费".equals(cost.getCostType()) && !"标准价".equals(cost.getPriceType()))
    //                             .max(Comparator.comparing(StaticPayCost::getBmsDealTime));
    //                 } else {
    //                     cost2 = lists.stream()
    //                             .filter(cost -> StringUtils.isNotBlank(cost.getPriceType())
    //                                     && cost.getPriceType().contains("暂估") && "运输费".equals(cost.getCostType()) && !"标准价".equals(cost.getPriceType()))
    //                             .max(Comparator.comparing(StaticPayCost::getGmtModify));
    //                 }
    //                 // Optional<StaticPayCost> cost2 = lists.stream()
    //                 //         .filter(cost -> StringUtils.isNotBlank(cost.getPriceType())
    //                 //                 && cost.getPriceType().contains("暂估") && "运输费".equals(cost.getCostType()) && !"标准价".equals(cost.getPriceType()))
    //                 //         .max(Comparator.comparing(StaticPayCost::getGmtModify));
    //                 if (cost2.isPresent()) {
    //                     if (Objects.isNull(staticWaybillComposite.getWaybillMiles()) || staticWaybillComposite.getWaybillMiles().compareTo(BigDecimal.ZERO) == 0) {
    //                         staticWaybillComposite.setWaybillMiles(cost2.get().getMiles());
    //                     }
    //                     if (Objects.isNull(staticWaybillComposite.getWaybillPrice()) || staticWaybillComposite.getWaybillPrice().compareTo(BigDecimal.ZERO) == 0) {
    //                         staticWaybillComposite.setWaybillPrice(cost2.get().getPrice());
    //                     }
    //                     if (Objects.isNull(staticWaybillComposite.getWaybillMoney()) || staticWaybillComposite.getWaybillMoney().compareTo(BigDecimal.ZERO) == 0) {
    //                         staticWaybillComposite.setWaybillMoney(cost2.get().getMoney());
    //                         staticWaybillComposite.setIsEst("是");
    //                     }
    //                     // 合同编码
    //                     staticWaybillComposite.setContractId(cost2.get().getContractId());
    //                     // 规则id
    //                     staticWaybillComposite.setQuoteCode(cost2.get().getRuleId());
    //                 }
    //
    //                 staticWaybillComposite.setWaybillMoney(Objects.isNull(staticWaybillComposite.getWaybillMoney()) ? BigDecimal.ZERO : staticWaybillComposite.getWaybillMoney());
    //                 //每种其他费用取一个最大值的和
    //                 // String costType = "运输费";
    //                 // List<StaticPayCost> cost3 = staticPayCostService.getPayOtherCostByCostType(costType, staticWaybillComposite.getSysWaybillId());
    //                 List<StaticPayCost> cost3 = Lists.newArrayList();
    //                 lists.stream()
    //                         .filter(cost -> !"运输费".equals(cost.getCostType()))
    //                         .forEach(cost -> {
    //                             cost3.add(cost);
    //                         });
    //                 BigDecimal otherCost = cost3.stream().map(StaticPayCost::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
    //                 staticWaybillComposite.setWaybillOtherCost(otherCost);
    //
    //                 BigDecimal payAmount;
    //                 if (Objects.nonNull(staticWaybillComposite.getPayBillOtherCost())) {
    //                     payAmount = staticWaybillComposite.getWaybillMoney().add(staticWaybillComposite.getWaybillOtherCost()).add(staticWaybillComposite.getPayBillOtherCost());
    //                 } else {
    //                     payAmount = staticWaybillComposite.getWaybillMoney().add(staticWaybillComposite.getWaybillOtherCost());
    //                 }
    //                 staticWaybillComposite.setPayAmount(payAmount);
    //
    //
    //                 //标准价
    //                 Optional<StaticPayCost> cost4 = lists.stream()
    //                         .filter(cost -> "运输费".equals(cost.getCostType()) && "标准价".equals(cost.getPriceType()))
    //                         .max(Comparator.comparing(StaticPayCost::getGmtModify));
    //                 if (cost4.isPresent()) {
    //                     staticWaybillComposite.setWaybillEstPrice(cost4.get().getPrice());
    //                     staticWaybillComposite.setWaybillEstMiles(cost4.get().getMiles());
    //                     staticWaybillComposite.setWaybillEstMoney(cost4.get().getMoney());
    //                     // 合同编码
    //                     staticWaybillComposite.setContractId(cost4.get().getContractId());
    //                     // 规则id
    //                     staticWaybillComposite.setQuoteCode(cost4.get().getRuleId());
    //                 }
    //
    //                 sysWaybillIdList.add(staticWaybillComposite.getSysWaybillId());
    //
    //                 updateWaybillCompositeList.add(staticWaybillComposite);
    //                 // this.update(staticWaybillComposite, ewStaticWaybillComposite);
    //             }
    //         });
    //
    //         if (CollectionUtils.isNotEmpty(updateWaybillCompositeList)) {
    //             this.updateBatchById(updateWaybillCompositeList);
    //         }
    //
    //         if (CollectionUtils.isNotEmpty(sysWaybillIdList)) {
    //             EntityWrapper<StaticPayCost> payCostEw = new EntityWrapper<>();
    //             payCostEw.in("sys_waybill_id", sysWaybillIdList);
    //             payCostEw.eq("deal_status", 0);
    //             StaticPayCost updatePayCost = new StaticPayCost();
    //             updatePayCost.setDealStatus(1);
    //             updatePayCost.setDealTime(dealDate);
    //             staticPayCostService.update(updatePayCost, payCostEw);
    //         }
    //
    //     } catch (Exception ex) {
    //         LOGGER.error("updatePrice {}", ex);
    //         throw new BaseException(ex.getMessage());
    //     }
    // }

    /**
     * 处理数据
     *
     * @param novoPayCostBoList
     */
    private void dealPayCostData(List<NovoPayCostBO> novoPayCostBoList) {
        Date currentDate = new Date();
        try {
            List<StaticWaybillComposite> updateWaybillCompositeList = Lists.newArrayList();
            List<StaticNovoPayCost> updatePayCostList = Lists.newArrayList();

            novoPayCostBoList.forEach(novoPayCost -> {
                StaticWaybillComposite staticWaybillComposite = this.selectById(novoPayCost.getSysWaybillCompositeId());
                if (Objects.nonNull(staticWaybillComposite)) {
                    // 单价
                    staticWaybillComposite.setWaybillPrice(novoPayCost.getPrice());
                    // 公里数
                    staticWaybillComposite.setWaybillMiles(novoPayCost.getMiles());
                    // 运输费
                    staticWaybillComposite.setWaybillMoney(novoPayCost.getFare());
                    // 是否暂估
                    staticWaybillComposite.setIsEst("否");
                    // 其他费用
                    staticWaybillComposite.setWaybillOtherCost(novoPayCost.getOtherFee());
                    // 总成本
                    staticWaybillComposite.setPayAmount(novoPayCost.getMoney());
                    // 开票单位
                    staticWaybillComposite.setPayName(novoPayCost.getUnlcnName());

                    updateWaybillCompositeList.add(staticWaybillComposite);

                    StaticNovoPayCost updatePayCost = new StaticNovoPayCost();
                    updatePayCost.setId(novoPayCost.getId());
                    updatePayCost.setDealStatus(1);
                    updatePayCost.setDealTime(currentDate);
                    updatePayCostList.add(updatePayCost);
                }
            });

            if (CollectionUtils.isNotEmpty(updateWaybillCompositeList)) {
                List<List<StaticWaybillComposite>> subList = BmsCollectionUtils.subListByNum(updateWaybillCompositeList, 1000);
                subList.forEach(list -> {
                    this.updateBatchById(list);
                });
            }

            if (CollectionUtils.isNotEmpty(updatePayCostList)) {
                List<List<StaticNovoPayCost>> subList = BmsCollectionUtils.subListByNum(updatePayCostList, 1000);
                subList.forEach(list -> {
                    staticNovoPayCostService.updateBatchById(list);
                });
            }

        } catch (Exception e) {
            LOGGER.error("dealPayCostData {}", e);
            throw new BaseException(e.getMessage());
        }
    }

    // /**
    //  * 更新原有应付价格状态
    //  *
    //  * @param distinctListPayCost
    //  */
    // private void updatePayCostStatus(List<StaticPayCost> distinctListPayCost) {
    //     Date date = new Date();
    //     //查询价格发生变化
    //     List<StaticPayCost> listPayCost = Lists.newArrayList();
    //
    //     distinctListPayCost.forEach(staticPayCost -> {
    //         EntityWrapper<StaticPayCost> ewCost = new EntityWrapper<>();
    //         ewCost.eq("sys_waybill_id", staticPayCost.getSysWaybillId())
    //                 .eq("deal_status", "0");
    //         List<StaticPayCost> listCosts = staticPayCostService.selectList(ewCost);
    //         listPayCost.addAll(listCosts);
    //     });
    //
    //     //更新原有价格状态
    //     listPayCost.forEach(staticPayCost -> {
    //         staticPayCost.setDealStatus(1);
    //         staticPayCost.setDealTime(date);
    //     });
    //
    //     if (CollectionUtils.isNotEmpty(listPayCost)) {
    //         staticPayCostService.updateBatchById(listPayCost);
    //     }
    // }


    // /**
    //  * 更新标准价
    //  *
    //  * @param distinctListPayCost
    //  */
    // private void updateStandPrice(List<StaticPayCost> distinctListPayCost) {
    //     try {
    //         distinctListPayCost.forEach(staticPayCost -> {
    //             EntityWrapper<StaticWaybillComposite> ewStaticWaybillComposite = new EntityWrapper<>();
    //             ewStaticWaybillComposite.eq("sys_order_id", staticPayCost.getSysOrderId())
    //                     .eq("sys_waybill_id", staticPayCost.getSysWaybillId());
    //             StaticWaybillComposite staticWaybillComposite = this.selectOne(ewStaticWaybillComposite);
    //
    //             if (Objects.nonNull(staticWaybillComposite)) {
    //                 EntityWrapper<StaticPayCost> staticPayCostEntityWrapper = new EntityWrapper<>();
    //                 staticPayCostEntityWrapper
    //                         .eq("sys_waybill_id", staticPayCost.getSysWaybillId())
    //                         .eq("cost_type", "运输费")
    //                         .eq("price_type", "标准价");
    //
    //                 List<StaticPayCost> lists = staticPayCostService.selectList(staticPayCostEntityWrapper);
    //
    //                 //标准价
    //                 Optional<StaticPayCost> cost4 = lists.stream().max(Comparator.comparing(StaticPayCost::getGmtModify));
    //                 if (cost4.isPresent()) {
    //                     staticWaybillComposite.setWaybillEstPrice(cost4.get().getPrice());
    //                     staticWaybillComposite.setWaybillEstMiles(cost4.get().getMiles());
    //                     staticWaybillComposite.setWaybillEstMoney(cost4.get().getMoney());
    //                     // 合同编码
    //                     staticWaybillComposite.setContractId(cost4.get().getContractId());
    //                     // 规则id
    //                     staticWaybillComposite.setQuoteCode(cost4.get().getRuleId());
    //                 }
    //
    //                 this.update(staticWaybillComposite, ewStaticWaybillComposite);
    //             }
    //         });
    //     } catch (Exception ex) {
    //         LOGGER.error("updateStandPrice {}", ex);
    //         throw new BaseException(ex.getMessage());
    //     }
    // }


    /**
     * 删除已经删除的运单
     *
     * @param deletedWaybillBOS
     */
    private void deleteWaybill(List<DeletedWaybillBO> deletedWaybillBOS) {
        try {

            List<StaticWaybill> listStaticWaybill = Lists.newArrayList();
            List<StaticDeleteWaybill> listDeleteWaybill = Lists.newArrayList();

            Date date = new Date();

            deletedWaybillBOS.forEach(deletedWaybillBO -> {
                //删除运单综合表中的数据
                EntityWrapper<StaticWaybillComposite> ewStaticWaybillComposite = new EntityWrapper<>();
                ewStaticWaybillComposite.eq("shipment_code", deletedWaybillBO.getShipmentCode())
                        .eq("sys_waybill_id", deletedWaybillBO.getSysWaybillId());
                this.delete(ewStaticWaybillComposite);

                //标识原有运单表中的数据为已删除状态
                EntityWrapper<StaticWaybill> ewStaticWaybill = new EntityWrapper<>();
                ewStaticWaybill.eq("shipment_code", deletedWaybillBO.getShipmentCode())
                        .eq("sys_waybill_id", deletedWaybillBO.getSysWaybillId());
                StaticWaybill staticWaybill = staticWaybillService.selectOne(ewStaticWaybill);
                if (Objects.nonNull(staticWaybill)) {
                    staticWaybill.setIsDelete(1);
                    listStaticWaybill.add(staticWaybill);
                }

                //删除表的标识
                EntityWrapper<StaticDeleteWaybill> ewStaticDeleteWaybill = new EntityWrapper<>();
                ewStaticDeleteWaybill.eq("shipment_code", deletedWaybillBO.getShipmentCode());
                StaticDeleteWaybill staticDeleteWaybill = staticDeleteWaybillService.selectOne(ewStaticDeleteWaybill);
                if (Objects.nonNull(staticDeleteWaybill)) {
                    staticDeleteWaybill.setDealStatus(1);
                    staticDeleteWaybill.setDealTime(date);
                    listDeleteWaybill.add(staticDeleteWaybill);
                }
            });

            if (CollectionUtils.isNotEmpty(listStaticWaybill)) {
                staticWaybillService.updateBatchById(listStaticWaybill);
            }

            if (CollectionUtils.isNotEmpty(listDeleteWaybill)) {
                staticDeleteWaybillService.updateBatchById(listDeleteWaybill);
            }
        } catch (Exception ex) {
            LOGGER.error("deleteWaybill {}", ex);
            throw new BaseException(ex.getMessage());
        }

    }

    /**
     * 更新运单的总收入
     *
     * @param nThreads
     */
    @Override
    public void updateAmount(int nThreads, int intCount) {
        EntityWrapper<StaticUpdateOrder> ewStaticUpdateOrder = new EntityWrapper<>();
        ewStaticUpdateOrder.eq("deal_status", 0);
        if (intCount > 0) {
            ewStaticUpdateOrder.last("limit " + intCount);
        }
        // ewStaticUpdateOrder.in("sys_order_id", getSysOrder());
        List<StaticUpdateOrder> updateOrders = staticUpdateOrderService.selectList(ewStaticUpdateOrder);
        if (CollectionUtils.isNotEmpty(updateOrders)) {
            int size = updateOrders.size();
            if (size <= 10) {
                nThreads = 1;
            }
            ExecutorService executorService1 = Executors.newFixedThreadPool(nThreads);
            int remaider = size % nThreads;  //(先计算出余数)
            int number = size / nThreads;  //然后是商
            int offset = 0;//偏移量
            try {
                for (int i = 0; i < nThreads; i++) {
                    // 先分组
                    if (remaider > 0) {
                        final List<StaticUpdateOrder> enrollList = updateOrders.subList(i * number + offset, (i + 1) * number + offset + 1);
                        executorService1.execute(() -> {
                            this.updateAmount(enrollList);
                        });
                        remaider--;
                        offset++;
                    } else {
                        final List<StaticUpdateOrder> enrollList = updateOrders.subList(i * number + offset, (i + 1) * number + offset);
                        executorService1.execute(() -> {
                            this.updateAmount(enrollList);
                        });
                    }
                }
                executorService1.shutdown();
                while (!executorService1.awaitTermination(60, TimeUnit.SECONDS)) {
                    LOGGER.info("updateAmount: 线程池没有关闭");
                }
                LOGGER.info("updateAmount: 线程池已经关闭");
            } catch (Exception ex) {
                LOGGER.error("updateAmount {}", ex);
                throw new BaseException(ex.getMessage());
            }
        }
    }


    /**
     * 计算分摊价格
     *
     * @param listStaticUpdateOrder
     */
    private void updateAmount(List<StaticUpdateOrder> listStaticUpdateOrder) {
        try {
            if (CollectionUtils.isNotEmpty(listStaticUpdateOrder)) {
                listStaticUpdateOrder.forEach(updateOrder -> {
                    if (Objects.nonNull(updateOrder.getSysOrderId())) {
                        //订单总收入
                        EntityWrapper<StaticOrderComposite> staticOrderCompositeEntityWrapper = new EntityWrapper<>();
                        staticOrderCompositeEntityWrapper.eq("sys_order_id", updateOrder.getSysOrderId());
                        StaticOrderComposite staticOrderComposite = staticOrderCompositeService.selectOne(staticOrderCompositeEntityWrapper);
                        if (Objects.nonNull(staticOrderComposite)) {
                            // 总收入
                            BigDecimal incomeAmount = Objects.nonNull(staticOrderComposite.getOrderIncomeAmount()) ? staticOrderComposite.getOrderIncomeAmount() : BigDecimal.ZERO;
                            // 申请开票金额
                            BigDecimal incomeInvoiceApply = Objects.nonNull(staticOrderComposite.getIncomeInvoiceApply()) ? staticOrderComposite.getIncomeInvoiceApply() : BigDecimal.ZERO;
                            // 已开票金额
                            BigDecimal incomeInvoiceMoney = Objects.nonNull(staticOrderComposite.getIncomeInvoiceMoney()) ? staticOrderComposite.getIncomeInvoiceMoney() : BigDecimal.ZERO;

                            //标准价总和
                            EntityWrapper<StaticWaybillComposite> staticWaybillCompositeEntityWrapper = new EntityWrapper<>();
                            staticWaybillCompositeEntityWrapper.eq("sys_order_id", updateOrder.getSysOrderId());
                            List<StaticWaybillComposite> lists = this.selectList(staticWaybillCompositeEntityWrapper);
                            if (CollectionUtils.isNotEmpty(lists)) {

                                BigDecimal sumEstMoney = BigDecimal.ZERO;
                                for (StaticWaybillComposite staticWaybillComposite : lists) {
                                    // if (Objects.nonNull(staticWaybillComposite.getWaybillEstMoney()) && staticWaybillComposite.getWaybillEstMoney().compareTo(BigDecimal.ZERO) > 0) {
                                    //     sumEstMoney = sumEstMoney.add(staticWaybillComposite.getWaybillEstMoney());
                                    // } else if (Objects.nonNull(staticWaybillComposite.getWaybillMoney()) && staticWaybillComposite.getWaybillMoney().compareTo(BigDecimal.ZERO) > 0) {
                                    //     sumEstMoney = sumEstMoney.add(staticWaybillComposite.getWaybillMoney());
                                    // }
                                    // 2019-07-01 修改 优先已成本为主
                                    if (Objects.nonNull(staticWaybillComposite.getWaybillMoney()) && staticWaybillComposite.getWaybillMoney().compareTo(BigDecimal.ZERO) > 0) {
                                        sumEstMoney = sumEstMoney.add(staticWaybillComposite.getWaybillMoney());
                                    } else if (Objects.nonNull(staticWaybillComposite.getWaybillEstMoney()) && staticWaybillComposite.getWaybillEstMoney().compareTo(BigDecimal.ZERO) > 0) {
                                        sumEstMoney = sumEstMoney.add(staticWaybillComposite.getWaybillEstMoney());
                                    }
                                }

                                for (StaticWaybillComposite staticWaybillComposite : lists) {
                                    staticWaybillComposite.setIncomeAmount(incomeAmount);
                                    if (sumEstMoney.compareTo(BigDecimal.ZERO) != 0) {
                                        BigDecimal incomeRatio = BigDecimal.ZERO;
                                        // if (Objects.nonNull(staticWaybillComposite.getWaybillEstMoney()) && staticWaybillComposite.getWaybillEstMoney().compareTo(BigDecimal.ZERO) > 0) {
                                        //     // 成本分摊系数
                                        //     incomeRatio = staticWaybillComposite.getWaybillEstMoney().divide(sumEstMoney, 4, RoundingMode.HALF_UP);
                                        // } else if (Objects.nonNull(staticWaybillComposite.getWaybillMoney()) && staticWaybillComposite.getWaybillMoney().compareTo(BigDecimal.ZERO) > 0) {
                                        //     // 成本分摊系数
                                        //     incomeRatio = staticWaybillComposite.getWaybillMoney().divide(sumEstMoney, 4, RoundingMode.HALF_UP);
                                        // }
                                        // 2019-07-01 修改 优先已成本为主
                                        if (Objects.nonNull(staticWaybillComposite.getWaybillMoney()) && staticWaybillComposite.getWaybillMoney().compareTo(BigDecimal.ZERO) > 0) {
                                            // 成本分摊系数
                                            incomeRatio = staticWaybillComposite.getWaybillMoney().divide(sumEstMoney, 4, RoundingMode.HALF_UP);
                                        } else if (Objects.nonNull(staticWaybillComposite.getWaybillEstMoney()) && staticWaybillComposite.getWaybillEstMoney().compareTo(BigDecimal.ZERO) > 0) {
                                            // 成本分摊系数
                                            incomeRatio = staticWaybillComposite.getWaybillEstMoney().divide(sumEstMoney, 4, RoundingMode.HALF_UP);
                                        }

                                        staticWaybillComposite.setIncomeRatio(incomeRatio);
                                        // 分摊收入
                                        BigDecimal incomeShare = incomeAmount.multiply(incomeRatio).setScale(2, RoundingMode.HALF_UP);
                                        staticWaybillComposite.setIncomeShare(incomeShare);
                                        // 分摊申请开票金额
                                        staticWaybillComposite.setShareInvoiceApply(incomeInvoiceApply.multiply(incomeRatio).setScale(2, BigDecimal.ROUND_HALF_UP));
                                        // 分摊已开票金额
                                        staticWaybillComposite.setShareInvoiceMoney(incomeInvoiceMoney.multiply(incomeRatio).setScale(2, BigDecimal.ROUND_HALF_UP));

                                        // this.updateById(staticWaybillComposite);
                                    }
                                }
                                this.updateBatchById(lists);
                            }
                        }
                        updateOrder.setDealStatus(1);
                        updateOrder.setDealTime(new Date());
                    }
                });
            }

            staticUpdateOrderService.updateBatchById(listStaticUpdateOrder);

        } catch (Exception ex) {
            LOGGER.error("updateAmount {}", ex);
            throw new BaseException(ex.getMessage());
        }
    }

    /**
     * 添加更新的订单号
     *
     * @param sysOrderId
     */
    private void addUpdateOrders(String sysOrderId) {
        EntityWrapper<StaticUpdateOrder> ewOrder = new EntityWrapper<>();
        ewOrder.eq("sys_order_id", sysOrderId);
        StaticUpdateOrder updateOrder = staticUpdateOrderService.selectOne(ewOrder);
        if (Objects.isNull(updateOrder)) {
            updateOrder = new StaticUpdateOrder();
            updateOrder.setSysOrderId(sysOrderId);
            updateOrder.setDealStatus(0);
        } else {
            updateOrder.setDealStatus(0);
        }
        staticUpdateOrderService.insertOrUpdate(updateOrder);
    }


    private void addOrUpdateOrder(List<String> sysOrderIdList) {
        int minLength = 1000;
        int sysOrderIdSize = sysOrderIdList.size();
        if (sysOrderIdSize > 1000) {
            int toIndex = minLength;
            for (int i = 0; i < sysOrderIdSize; i += minLength) {
                if (i + minLength > sysOrderIdSize) {
                    toIndex = sysOrderIdSize - i;
                }
                List<String> newSysOrderIdList = sysOrderIdList.subList(i, i + toIndex);
                batchDealSysOrderId(newSysOrderIdList);
            }
        } else {
            batchDealSysOrderId(sysOrderIdList);
        }
    }

    private void batchDealSysOrderId(List<String> sysOrderIdList) {
        EntityWrapper<StaticUpdateOrder> ewOrder = new EntityWrapper<>();
        ewOrder.in("sys_order_id", sysOrderIdList);

        StaticUpdateOrder updateOrder = new StaticUpdateOrder();
        updateOrder.setDealStatus(0);
        staticUpdateOrderService.update(updateOrder, ewOrder);

        ewOrder.setSqlSelect("sys_order_id");
        List<Object> objectList = staticUpdateOrderService.selectObjs(ewOrder);
        if (CollectionUtils.isNotEmpty(objectList)) {
            List<String> objStrList = Lists.newArrayList();
            objectList.forEach(obj -> {
                objStrList.add(obj.toString());
            });

            List<StaticUpdateOrder> insertOrderList = Lists.newArrayList();
            sysOrderIdList.forEach(sysOrder -> {
                if (!objStrList.contains(sysOrder)) {
                    StaticUpdateOrder insertStaticOrder = new StaticUpdateOrder();
                    insertStaticOrder.setSysOrderId(sysOrder);
                    insertStaticOrder.setDealStatus(0);
                    insertOrderList.add(insertStaticOrder);
                }
            });
            if (CollectionUtils.isNotEmpty(insertOrderList)) {
                staticUpdateOrderService.insertBatch(insertOrderList);
            }
        } else {
            List<StaticUpdateOrder> updateOrderList = Lists.newArrayList();
            sysOrderIdList.forEach(sysOrder -> {
                StaticUpdateOrder updateStaticOrder = new StaticUpdateOrder();
                updateStaticOrder.setSysOrderId(sysOrder);
                updateStaticOrder.setDealStatus(0);
                updateOrderList.add(updateStaticOrder);
            });
            if (CollectionUtils.isNotEmpty(updateOrderList)) {
                staticUpdateOrderService.insertBatch(updateOrderList);
            }
        }
    }

    /**
     * 得到导出文件的表头
     *
     * @return
     */
    @Override
    public Map<String, Object> getOrderWaybillDataMap() {
        Map<String, Object> maps = Maps.newLinkedHashMap();

        maps.put("sysWaybillId", "系统运单号");
        maps.put("sysOrderId", "系统订单号");
        maps.put("custWaybillId", "客户运单号");
        maps.put("despatchDate", "发运日期");
        maps.put("printDate", "打印日期");
        maps.put("returnDate", "回单日期");
        maps.put("incomeInvoiceDate", "开票日期");

        maps.put("receiptDate", "收款日期");
        maps.put("ciams", "业务主体");
        maps.put("customerId", "客户名称");
        maps.put("carTypeName", "车型");
        maps.put("standardCarName", "标准车型");
        maps.put("orderStartAddr", "起运地");
        maps.put("orderEndAddr", "目的地");
        maps.put("orderReleaseType", "当前节点");
        maps.put("orderMiles", "收入公里");
        maps.put("orderPrice", "收入单价");

        maps.put("orderNum", "结算数量");
        maps.put("orderOtherCost", "订单其他费用");
        maps.put("incomeBillOtherCost", "应收账单其他费用分摊金额");
        maps.put("orderMoney", "运输费");
        maps.put("incomeAmount", "总收入");
        maps.put("arRecMoney", "回款金额");
        maps.put("shipmentCode", "指令号");
        maps.put("incomeShare", "分摊收入");
        maps.put("shareInvoiceApply", "分摊申请开票金额");
        maps.put("shareInvoiceMoney", "分摊已开票金额");
        maps.put("incomeRatio", "成本分摊系数");

        maps.put("lsp", "承运商");
        maps.put("fleet", "车队");
        maps.put("plate", "车牌号");
        maps.put("waybillStartAddr", "司机起运地");
        maps.put("waybillEndAddr", "司机目的地");
        maps.put("waybillMiles", "支付公里");
        maps.put("shipNum", "发运数量");
        maps.put("waybillPrice", "支付单价");
        maps.put("waybillOtherCost", "运单其他费用");
        maps.put("payBillOtherCost", "应付账单其他费用分摊金额");

        maps.put("waybillMoney", "运输成本");
        maps.put("payAmount", "支付成本");
        maps.put("payBillStatus", "支付状态");
        maps.put("orderEndProvince", "订单省份");
        maps.put("waybillEndProvince", "指令省份");
        maps.put("waybillStatus", "运单状态");
        maps.put("isEstPrice", "应收单价暂估");
        maps.put("isEstMiles", "应收公里暂估");
        maps.put("isEst", "应付单价暂估");
        maps.put("unitName", "开票公司");

        maps.put("payInvoiceCode", "支付申请单号");
        maps.put("payInvoiceNo", "支付发票号");
        maps.put("payInvoiceDate", "支付开票日期");
        maps.put("payDate", "支付日期");
        maps.put("incomeInvoiceStatus", "开票状态");
        maps.put("incomeInvoiceNo", "收入发票号");
        maps.put("receiveInvoiceDate", "财务收票日期");
        maps.put("incomeInvoiceApply", "申请开票金额");
        maps.put("incomeInvoiceMoney", "已开票金额");
        maps.put("payName", "支付主体");
        // maps.put("waybillEstMoney", "成本标准价");
        maps.put("payMoney", "已确认支付金额");
        maps.put("transportMode", "运输工具类型");
        maps.put("mainTransportMode", "订单主运输方式");
        // maps.put("waybillEstMiles", "支付标准公里");
        // maps.put("waybillEstPrice", "支付标准单公里价");
        maps.put("discount", "分供方扣点");
        maps.put("quoteCode", "报价单号");
        maps.put("orderStatus", "订单状态");

        return maps;
    }

    /**
     * 格式排除字段
     *
     * @return
     */
    @Override
    public List<String> getExcludeList() {
        List<String> excludeLists = Lists.newArrayList();

        excludeLists.add("sysWaybillId");
        excludeLists.add("sysOrderId");
        excludeLists.add("custWaybillId");

        excludeLists.add("payInvoiceNo");
        excludeLists.add("incomeInvoiceNo");
        excludeLists.add("payInvoiceCode");

        return excludeLists;

    }

    /**
     * 更新合同和暂估价
     *
     * @param nThreads
     * @param intCount
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updateWaybillContractAndEstPrice(int nThreads, int intCount) {
        List<StaticWaybillComposite> compositeList = getWaybillCompostiteList(intCount);
        if (CollectionUtils.isNotEmpty(compositeList)) {
            try {
                ExecutorService executorService1 = Executors.newFixedThreadPool(nThreads);
                int size = compositeList.size();
                if (size <= 10) {
                    nThreads = 1;
                }
                int remaider = size % nThreads;  //(先计算出余数)
                int number = size / nThreads;  //然后是商
                for (int i = 0; i < nThreads; i++) {
                    List<StaticWaybillComposite> subCompositeList = null;
                    if ((i + 1) == nThreads) {
                        subCompositeList = compositeList.subList(i * number, ((i + 1) * number) + remaider);
                    } else {
                        subCompositeList = compositeList.subList(i * number, (i + 1) * number);
                    }
                    List<StaticWaybillComposite> finalSubCompositeList = subCompositeList;
                    executorService1.execute(() -> {
                        updateBatchComposite(finalSubCompositeList);
                    });
                }
                executorService1.shutdown();
                while (!executorService1.awaitTermination(60, TimeUnit.SECONDS)) {
                    LOGGER.info("updateWaybillContractAndEstPrice: 线程池没有关闭");
                }
                LOGGER.info("updateWaybillContractAndEstPrice: 线程池已经关闭");
            } catch (Exception e) {
                LOGGER.error("updateWaybillContractAndEstPrice: {}", e);
                throw new BaseException(e.getMessage());
            }
        }
    }

    /**
     * 更新运单和订单
     *
     * @param compositeList
     */
    private void updateBatchComposite(List<StaticWaybillComposite> compositeList) {
        List<StaticOrderComposite> updateStaticOrderCompositeList = Lists.newArrayList();
        compositeList.stream()
                .filter(composite -> StringUtils.isNotBlank(composite.getSysWaybillId()))
                .forEach(composite -> {
                    // TODO 根据OR查询处理
                    FeePayablePrice feePayablePrice = feePayablePriceService.getFeePayablePriceByWaybillId(composite.getSysWaybillId(), TRANSPORT_PRICE);
                    FeePayablePrice otherFeePayablePrice = feePayablePriceService.getFeePayablePriceByWaybillId(composite.getSysWaybillId(), OTHER_PRICE);
                    if (feePayablePrice != null) {
                        // 运输费
                        StaticOrderComposite staticOrderComposite = updateTransportPrice(composite, feePayablePrice);
                        if (staticOrderComposite != null) {
                            updateStaticOrderCompositeList.add(staticOrderComposite);
                        }
                    }
                    if (otherFeePayablePrice != null) {
                        // 其他费用
                        composite.setWaybillOtherCost(otherFeePayablePrice.getElsePrice() == null ? BigDecimal.ZERO : otherFeePayablePrice.getElsePrice());
                    }
                    // 账款扣款其他均摊费用
                    composite.setPayBillOtherCost(feeBillService.getFeeBillDuceSumByDtlWaybillId(composite.getSysWaybillId()));
                    // 总成本
                    if (composite.getWaybillEstMoney() != null && composite.getWaybillOtherCost() != null) {
                        composite.setDiscount(composite.getWaybillEstMoney().add(composite.getWaybillOtherCost()));
                    }
                });
        // 更新
        this.updateBatchById(compositeList);
        if (CollectionUtils.isNotEmpty(updateStaticOrderCompositeList)) {
            staticOrderCompositeService.updateBatchById(updateStaticOrderCompositeList);
        }
    }

    /**
     * 更新运输费
     *
     * @param composite
     * @param feePayablePrice
     */
    private StaticOrderComposite updateTransportPrice(StaticWaybillComposite composite, FeePayablePrice feePayablePrice) {
        // 合同价
        BigDecimal kilometre = feePayablePrice.getKilometre() == null ? BigDecimal.ZERO : feePayablePrice.getKilometre();
        BigDecimal price = feePayablePrice.getPrice() == null ? BigDecimal.ZERO : feePayablePrice.getPrice();
        composite.setWaybillEstMiles(kilometre);
        composite.setWaybillPrice(price);
        // 运费
        composite.setWaybillMoney(price.multiply(kilometre));
        // 报价单号
        composite.setQuoteCode(feePayablePrice.getQuoteCode());
        // 合同号
        composite.setContractId(feePayablePrice.getContractCode());
        // 分供方扣点
        composite.setDiscount(feePayablePrice.getRate());
        if (CONTRACT_PRICE.equals(feePayablePrice.getPriceType())) {
            composite.setIsEst("否");
        } else if (STAND_PRICE.equals(feePayablePrice.getPriceType())) {
            composite.setIsEst("是");
        }

        // 查询订单统计
        EntityWrapper<StaticOrderComposite> ew = new EntityWrapper<>();
        ew.eq("sys_order_id", composite.getSysOrderId());
        List<StaticOrderComposite> staticOrderCompositeList = staticOrderCompositeService.selectList(ew);
        if (CollectionUtils.isNotEmpty(staticOrderCompositeList)) {
            StaticOrderComposite staticOrderComposite = staticOrderCompositeList.get(0);
            staticOrderComposite.setContractId(composite.getContractId());
            staticOrderComposite.setRuleId(composite.getQuoteCode());
            return staticOrderComposite;
        }
        return null;
    }

    /**
     * 获取需要编辑处理的数据
     *
     * @param intCount
     * @return
     */
    private List<StaticWaybillComposite> getWaybillCompostiteList(int intCount) {
        EntityWrapper<StaticWaybillComposite> ew = new EntityWrapper<>();
        ew.isNull("waybill_money");
        ew.orderBy("gmt_create asc");
        if (intCount > 0) {
            Page<StaticWaybillComposite> page = new Page<>(1, intCount);
            return baseMapper.getWaitFeePayablePriceCompositePage(page, ew);
        } else {
            return baseMapper.getWaitFeePayablePriceComposite(ew);
        }
    }


    /**
     * 拼装查询条件
     *
     * @param page
     * @return
     */
    private EntityWrapper<OrderWaybillBO> whereCondition(Page<OrderWaybillBO> page) {
        EntityWrapper<OrderWaybillBO> ew = new EntityWrapper<>();
        Map<String, Object> condition = page.getCondition();
        if (condition != null) {
            // 打印时间
            if (Objects.nonNull(condition.get("printDateStart"))) {
                ew.ge("print_date", page.getCondition().get("printDateStart").toString().trim());
            }
            // 打印结束时间
            if (Objects.nonNull(condition.get("printDateEnd"))) {
                ew.le("print_date", page.getCondition().get("printDateEnd").toString().trim());
            }
            // 开票时间
            if (Objects.nonNull(condition.get("incomeInvoiceDateStart"))) {
                ew.ge("income_invoice_date", page.getCondition().get("incomeInvoiceDateStart").toString().trim());
            }
            // 开票时间
            if (Objects.nonNull(condition.get("incomeInvoiceDateEnd"))) {
                ew.le("income_invoice_date", page.getCondition().get("incomeInvoiceDateEnd").toString().trim());
            }
            // 财务收票时间 - receive_invoice_date receiveInvoiceDate
            if (Objects.nonNull(condition.get("receiveInvoiceDateStart"))) {
                ew.ge("receive_invoice_date", page.getCondition().get("receiveInvoiceDateStart").toString().trim());
            }
            // 财务收票时间 - receive_invoice_date receiveInvoiceDate
            if (Objects.nonNull(condition.get("receiveInvoiceDateEnd"))) {
                ew.le("receive_invoice_date", page.getCondition().get("receiveInvoiceDateEnd").toString().trim());
            }
            // 系统订单号
            Object sysOrderId = condition.get("sysOrderId");
            if (Objects.nonNull(sysOrderId) && StringUtils.isNotBlank(sysOrderId.toString())) {
                ew.eq("sys_order_id", sysOrderId.toString());
            }
            // 多个系统订单号
            Object sysOrderIdArray = condition.get("sysOrderIdArray");
            if (Objects.nonNull(sysOrderIdArray) && StringUtils.isNotBlank(sysOrderIdArray.toString())) {
                ew.in("sys_order_id", ToolCommonUtils.getStringByObjectReplace(sysOrderIdArray));
            }
            // 多个系统运单号
            Object sysWaybillIdArray = condition.get("sysWaybillIdArray");
            if (Objects.nonNull(sysWaybillIdArray) && StringUtils.isNotBlank(sysWaybillIdArray.toString())) {
                ew.in("sys_waybill_id", ToolCommonUtils.getStringByObjectReplace(sysWaybillIdArray));
            }
            // 多个收入发票号
            Object incomeInvoiceNoArray = condition.get("incomeInvoiceNoArray");
            if (Objects.nonNull(incomeInvoiceNoArray) && StringUtils.isNotBlank(incomeInvoiceNoArray.toString())) {
                // ew.in("income_invoice_no", ToolCommonUtils.getStringByObjectReplace(incomeInvoiceNoArray));
                String income_invoice_no = getSqlLocate("income_invoice_no", ToolCommonUtils.getStringByObjectReplace(incomeInvoiceNoArray));
                ew.where(" (" + income_invoice_no + ")");
            }
            // 多个支付申请单号
            Object payInvoiceCodeArray = condition.get("payInvoiceCodeArray");
            if (Objects.nonNull(payInvoiceCodeArray) && StringUtils.isNotBlank(payInvoiceCodeArray.toString())) {
                // ew.in("pay_invoice_code", ToolCommonUtils.getStringByObjectReplace(payInvoiceCodeArray));
                String pay_invoice_code = getSqlLocate("pay_invoice_code", ToolCommonUtils.getStringByObjectReplace(payInvoiceCodeArray));
                ew.where(" (" + pay_invoice_code + ")");
            }
            // 发运日期 - 开始
            if (Objects.nonNull(condition.get("dispatchDateStart"))) {
                ew.ge("despatch_date", page.getCondition().get("dispatchDateStart").toString().trim());
            }
            // 发运日期 - 结束
            if (Objects.nonNull(condition.get("dispatchDateEnd"))) {
                ew.le("despatch_date", page.getCondition().get("dispatchDateEnd").toString().trim());
            }
        }
        return ew;
    }

    private EntityWrapper<OrderWaybillBO> whereCondition(OrderWaybillQueryVO queryVO) {
        EntityWrapper<OrderWaybillBO> ew = new EntityWrapper<>();
        // 打印时间
        if (StringUtils.isNotBlank(queryVO.getPrintDateStart())) {
            ew.ge("print_date", queryVO.getPrintDateStart());
        }

        if (StringUtils.isNotBlank(queryVO.getPrintDateEnd())) {
            ew.le("print_date", queryVO.getPrintDateEnd());
        }
        // 开票时间
        if (Objects.nonNull(queryVO.getIncomeInvoiceDateStart())) {
            ew.ge("income_invoice_date", queryVO.getIncomeInvoiceDateStart());
        }
        // 开票时间
        if (Objects.nonNull(queryVO.getIncomeInvoiceDateEnd())) {
            ew.le("income_invoice_date", queryVO.getIncomeInvoiceDateEnd());
        }
        // 财务收票时间 - receive_invoice_date receiveInvoiceDate
        if (Objects.nonNull(queryVO.getReceiveInvoiceDateStart())) {
            ew.ge("receive_invoice_date", queryVO.getReceiveInvoiceDateStart());
        }
        // 财务收票时间 - receive_invoice_date receiveInvoiceDate
        if (Objects.nonNull(queryVO.getReceiveInvoiceDateEnd())) {
            ew.le("receive_invoice_date", queryVO.getReceiveInvoiceDateEnd());
        }
        // 系统订单号
        if (StringUtils.isNotBlank(queryVO.getSysOrderId())) {
            ew.eq("sys_order_id", queryVO.getSysOrderId());
        }
        // 多个系统订单号
        if (StringUtils.isNotBlank(queryVO.getSysOrderIdArray())) {
            ew.in("sys_order_id", ToolCommonUtils.getStringByObjectReplace(queryVO.getSysOrderIdArray()));
        }
        // 多个系统运单号
        if (StringUtils.isNotBlank(queryVO.getSysWaybillIdArray())) {
            ew.in("sys_waybill_id", ToolCommonUtils.getStringByObjectReplace(queryVO.getSysWaybillIdArray()));
        }
        // 多个收入发票号
        if (StringUtils.isNotBlank(queryVO.getIncomeInvoiceNoArray())) {
            // ew.in("income_invoice_no", ToolCommonUtils.getStringByObjectReplace(queryVO.getIncomeInvoiceNoArray()));
            String income_invoice_no = getSqlLocate("income_invoice_no", ToolCommonUtils.getStringByObjectReplace(queryVO.getIncomeInvoiceNoArray()));
            ew.where(" (" + income_invoice_no + ")");
        }
        // 多个支付申请单号
        if (StringUtils.isNotBlank(queryVO.getPayInvoiceCodeArray())) {
            // ew.in("pay_invoice_code", ToolCommonUtils.getStringByObjectReplace(queryVO.getPayInvoiceCodeArray()));
            String pay_invoice_code = getSqlLocate("pay_invoice_code", ToolCommonUtils.getStringByObjectReplace(queryVO.getPayInvoiceCodeArray()));
            ew.where(" (" + pay_invoice_code + ")");
        }
        // 发运日期 - 开始
        if (Objects.nonNull(queryVO.getDispatchDateStart())) {
            ew.ge("despatch_date", queryVO.getDispatchDateStart());
        }
        // 发运日期 - 结束
        if (Objects.nonNull(queryVO.getDispatchDateEnd())) {
            ew.le("despatch_date", queryVO.getDispatchDateEnd());
        }
        return ew;
    }

    private String getSqlLocate(String cloum, String[] conditionArray) {
        if (conditionArray != null && conditionArray.length > 0) {
            StringBuilder sb = new StringBuilder();
            Arrays.stream(conditionArray).forEach(condition -> {
                if (sb.length() > 0) {
                    sb.append(" or ");
                }
                sb.append("locate(").append("'").append(condition).append("'")
                        .append(", ").append(cloum).append(")");
            });
            return sb.toString();
        }
        return null;
    }

    // private List<String> getSysWaybillId() {
    //     List<String> sysWaybillIdList = Lists.newArrayList();
    //     sysWaybillIdList.add("OR2019040600330");
    //     sysWaybillIdList.add("OR2019012402411");
    //     return sysWaybillIdList;
    // }
    //
    //
    // private List<String> getSysOrder() {
    //     List<String> sysOrderList = Lists.newArrayList();
    //     sysOrderList.add("X190100973");
    //     sysOrderList.add("X190100953");
    //     return sysOrderList;
    // }

    /**
     * 成本缺失明细
     *
     * @return
     */
    @Override
    public Map<String, Object> getCostMissingDetailExportMap() {
        Map<String, Object> costMissingDetailMap = Maps.newLinkedHashMap();
        costMissingDetailMap.put("ciams", "业务主体");
        costMissingDetailMap.put("shipmentCode", "调度指令号");
        costMissingDetailMap.put("sysWaybillId", "系统运单号");
        costMissingDetailMap.put("sysOrderId", "系统订单号");
        costMissingDetailMap.put("custWaybillId", "客户运单号");
        costMissingDetailMap.put("despatchDate", "发运日期");
        costMissingDetailMap.put("transportMode", "运输方式");
        costMissingDetailMap.put("lsp", "分供方");
        //costMissingDetailMap.put("lspId", "分供方id");
        //costMissingDetailMap.put("feeltId", "车队id");
        costMissingDetailMap.put("fleet", "车队");
        costMissingDetailMap.put("plate", "车牌号码");
        costMissingDetailMap.put("waybillCarTypeName", "车型");
        costMissingDetailMap.put("shipNum", "数量");
        costMissingDetailMap.put("waybillStartAddr", "起运地");
        costMissingDetailMap.put("waybillEndAddr", "目的地");
        costMissingDetailMap.put("waybillEndProvince", "目的省份");
        costMissingDetailMap.put("orderReleaseType", "当前节点");
        costMissingDetailMap.put("waybillStatus", "运单状态");
        costMissingDetailMap.put("podStatus", "回单状态");
        costMissingDetailMap.put("waybillPrice", "支付单价");
        costMissingDetailMap.put("waybillMiles", "支付公里");
        costMissingDetailMap.put("waybillEstPrice", "标准单价");
        costMissingDetailMap.put("waybillEstMiles", "标准公里数");
        costMissingDetailMap.put("waybillEstMoney", "标准总价");
        costMissingDetailMap.put("waybillMoney", "运输费");
        costMissingDetailMap.put("waybillOtherCost", "运单其他费用");
        costMissingDetailMap.put("payAmount", "总成本");
        return costMissingDetailMap;
    }

    /**
     * 成本缺失明细 导出
     *
     * @return
     */
    @Override
    public List<WaybillCompositeVO> getCostMissingDetail() {
        return baseMapper.getCostMissingDetail();
    }
}


